package com.group6.companymanagement.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group6.companymanagement.entity.Dept;
import com.group6.companymanagement.entity.Position;
import com.group6.companymanagement.service.DeptService;
import com.group6.companymanagement.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PositionController {
    @Autowired
    DeptService deptService;
    @Autowired
    PositionService positionService;

    // 查询所有
    @GetMapping("/positions")
    public String list(Model model, @RequestParam(value="pageNum",defaultValue="1")Integer pageNum) {
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum= 1;
        }
        //设置分页(当前页，和每页显示数据条数)
        PageHelper.startPage(pageNum, 10);

        List<Position> positions = positionService.getAllPositions();

        PageInfo<Position> pageInfo=new PageInfo<>(positions);
        //用Model传递对象到page页面
        model.addAttribute("pageInfo",pageInfo);
        return "position/position";
    }

    // 来到添加页面
    @GetMapping("/position")
    public String toAddPage(Model model) {
        // 来到添加页面
        List<Dept> depts = deptService.getAllDepts();
        model.addAttribute("depts",depts);

        return "position/add";
    }

    // 添加
    @PostMapping("/position")
    public String addPosition(Position position) {
        // 保存
        positionService.addPosition(position);

        return "redirect:/positions";
    }

    // 来到修改页面
    @GetMapping("/position/{id}")
    public String toUpdatePage(@PathVariable("id") Integer id, Model model) {
        Position position = positionService.getPositionById(id);
        model.addAttribute("position",position);
        // 页面要显示所有的部门列表
        List<Dept> depts = deptService.getAllDepts();
        model.addAttribute("depts",depts);

        return "position/add";
    }

    // 修改，需要提交id
    @PutMapping("/position")
    public String updatePosition(Position position) {
        positionService.updatePosition(position);
        return "redirect:/positions";
    }

    //删除
    @DeleteMapping("/position/{id}")
    public String deletePositionById(@PathVariable("id") Integer id){
        positionService.deletePositionById(id);
        return "redirect:/positions";
    }
}
